package py.com.fms.gnd.session.maintenances;

//External classes imports 
//Java Classes
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

//Seam Classes
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

//project classes imports

// BEANS
import py.com.fms.fms.bean.UsersBean;
import py.com.fms.gnd.bean.RacesBean;

// SERVICES
import py.com.fms.fms.persistence.services.UsersServices;
import py.com.fms.gnd.persistence.services.RacesServices;

// OTHERS
import py.com.fms.exception.CommonException;
import py.com.fms.session.ServiceSqlMap;
import py.com.fms.session.WithinHolder;
import py.com.fms.utilities.ConvertAssistant;
import py.com.fms.utilities.DateAssistant;
import py.com.fms.utilities.FormAssistant;

@SuppressWarnings("unused")
@Name("editRace")
@Scope(ScopeType.SESSION)
public class EditRaces {
	
	private FacesMessages facesMessages;
	@Logger
	private Log log;
	@In("#{serviceSqlMap}")
	private ServiceSqlMap sqlMap;
	private String initVar;
	private Date today = null;
	
	// Task Attendees Attributes 
	@In("#{withinHolder}")
	private WithinHolder aid;
	@In("#{convertAssist}")
	private ConvertAssistant convert;
	@In Credentials credentials;
	@In Identity identity;
	private DateAssistant dateAssist;
	private FormAssistant formAssist;
	
	
	// Beans
	private UsersBean user = null; // For User Data 
	private RacesBean race = null; // Used in main forms
	private RacesBean editRace = null; // Used for update operations

	// Services
	private UsersServices usSrv;
	private RacesServices rcSrv;
		
	// Collections
	private Collection<RacesBean> allRaces; // Used to store all object data
	
	// Necessary Attributes
	private Boolean validateEntireForm = true;
	private Boolean validForm;

	/**
	 * [[[[[[[[[[[[ Methods ]]]]]]]]]]]] 
	 * [[[[[[[[[[-------------]]]]]]]]]]
	 */

	// Used to initialize Objects
	public void initData() throws CommonException {

		System.out.println("Initialization Flag = " + this.getInitVar());

		if ("S".equals(this.getInitVar())) { // Checking initialization Flag
			this.loadUserData(); // Retrieving User Data
			this.initBeans(); // Initializing Beans
			this.initServices(); // Initializing Services
			this.initAssistants(); // Initializing Assistants
			this.initCollections(); // Initializing Collections
			this.loadDataGrid(); // Loading data for grid
			
		}
		this.setInitVar(null);
		System.out.println("OUT");
				
	}
	
	
    private void initBeans(){
    	
	  	if(race == null){
	  		race = new RacesBean();
	  		race.setStatus(true);
	  	}
	  	
	  	if(editRace == null){
	  		editRace = new RacesBean();
	  	}
	
    }
    
    private void initServices() throws CommonException{
    	
    	if (rcSrv == null){
			rcSrv = new RacesServices(this.sqlMap.getConfig());
		}
		
    	
    }
    
    private void initAssistants(){
    	
    	if(aid == null){
    		aid = new WithinHolder();
    	}
    	
    	if(convert == null){
			convert = new ConvertAssistant();
		}
    	
    	if(dateAssist == null){
			dateAssist = new DateAssistant();
		}
    	
    	if(formAssist == null){
			formAssist = new FormAssistant();
		}
    	
    }
    
    private void initCollections(){
    	
    	if(allRaces == null){
    		allRaces = new ArrayList<RacesBean>();
    	}
    }
    
    // Used to clean all objects
    public void cleanData() throws CommonException{
    	
    	// Cleaning Beans
  		user = null;
  		race = null;
  		editRace = null;

  		// Cleaning Services
		rcSrv = null;
		usSrv = null;

		// Cleaning Assistants
		aid = null;
		convert = null;
		dateAssist = null;
		formAssist = null;
		
		// Cleaning Collections
		allRaces = null;
    	
    }
    
    private void loadUserData() throws CommonException {
		System.out.println("Iniciando usuario compra");
		if (user == null) {
			user = new UsersBean();
		}
		if (usSrv == null) {
			usSrv = new UsersServices(this.sqlMap.getConfig());
		}
		System.out.println("Antes de credential");
		if (user != null && credentials != null) {
			System.out.println("Credenciales Encontradas: " + credentials + "User: " + user);
			this.getUser().setUserName(credentials.getUsername());
			System.out.println("User Name: " + this.getUser().getUserName());
			try {
				this.setUser(usSrv.getUserDataByName(this.getUser().getUserName().toUpperCase().trim()));
			} catch (Exception e) {
				System.out.println("ERROR: " + e.getMessage());
			}
			
			this.setUser(this.user);
			System.out.println("User: " + this.getUser());
			System.out.println("User ENT: " + this.getUser().getIdEnt());
			System.out.println("User BRANCH: " + this.getUser().getDefaultBranch());
		} else {
			System.out.println("Credenciales Nulas");
		}
		System.out.println("Despues de credentials");
	}
    
 // Used to load a grid using a collection
	private void loadDataGrid() {
		try {
			this.setAllRaces(rcSrv.getAllRaces());
			for (RacesBean race : this.getAllRaces()) {
				System.out.println(race.getCod() + " - " + race.getDescrip());
			}
		} catch (CommonException e) {
			e.printStackTrace();
		}
	}

	// Used to cancel
	public void cancelData() throws CommonException {
//		this.facesMessages.clear();
		this.cleanData(); // Cleaning Objects
		this.setInitVar("S"); // Setting initialization Flag
		this.initData();
	}

		

	// Used for data saving process
	public void saveNewData() throws ParseException, CommonException {
		try {
//			this.facesMessages.clear();
			this.validForm = false;
			this.setValidateEntireForm(true);
			RacesBean newRace = new RacesBean(); // Instantiating a object for saving


			if (this.getRace() == null) {
				System.out.println("this.getRace() == null");
				throw new CommonException("error.fms.menu.error.countrynotexist");
			}
			System.out.println("Before Setting Fields");
			
			// Validate Fields
			if(formAssist.stringValidate(this.getRace().getCod(), true).equals(false)){
				this.validForm = false;
				return;
			}
			if(formAssist.stringValidate(this.getRace().getDescrip(), true).equals(false)){
				this.validForm = false;
				return;
			}
			this.validForm = true;
			
			// Setting field values
			newRace.setCod(this.convert.convertField(this.getRace().getCod()));
			newRace.setDescrip(this.convert.convertField(this.getRace().getDescrip()));
			newRace.setStatus(this.getRace().getStatus());
			newRace.setStartDate(DateAssistant.getHoleDateTime());
			System.out.println(DateAssistant.getHoleDateTime());
			newRace.setUserIns(user.getId());
			
			System.out.println("Valid Form?, "+this.validForm);
			if(this.validForm.equals(true)){
				rcSrv.saveNewRace(newRace);
				this.setValidateEntireForm(false);
				this.cleanData(); // Cleaning Objects
				this.setInitVar("S"); // Setting initialization Flag
				this.initData();
			}
			
			
			
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO INSERTAR. " + e.getMessage());
			log.error(e);
		}

	}
	
	// Retrieving data for updating
	public void dataToEdit(Long id){
		System.out.println("id = " + id.toString());
		for (RacesBean bean : this.getAllRaces()) {
			if(bean.getId().equals(id)){
				this.setEditRace(bean);
				return;
			}			
		}	
	}
	
	// Updating Data in Database
	public void dataToEditUpd() throws ParseException{
		try {

			rcSrv.updateRace(this.getEditRace());
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO ACTUALIZAR EL REG. " + e.getMessage());
			log.error(e);
		}
	}
	
	// Deleting Data from Database
	public void dataToDelete(Long id){
		for (RacesBean bean: this.getAllRaces()){
			if (bean.getId().equals(id)) {
				try {
					rcSrv.deleteRaceById(bean.getId());
					
				} catch (Exception e) {
//					this.facesMessages.add(Severity.ERROR, e.getMessage());
					System.out.println("NO SE BORRAR EL REGISTRO. " + e.getMessage());
					log.error(e);
				}
			}
			
		}
		this.setInitVar("S");
	}
	
	// MUTATORS AND ACCESORS
	public FacesMessages getFacesMessages() {
		return facesMessages;
	}

	public void setFacesMessages(FacesMessages facesMessages) {
		this.facesMessages = facesMessages;
	}

	public Log getLog() {
		return log;
	}

	public void setLog(Log log) {
		this.log = log;
	}

	public ServiceSqlMap getSqlMap() {
		return sqlMap;
	}

	public void setSqlMap(ServiceSqlMap sqlMap) {
		this.sqlMap = sqlMap;
	}


	public String getInitVar() {
		return initVar;
	}

	public void setInitVar(String initVar) {
		this.initVar = initVar;
	}

	public RacesBean getRace() {
		return race;
	}

	public void setRace(RacesBean race) {
		this.race = race;
	}

	public Collection<RacesBean> getAllRaces() {
		return allRaces;
	}

	public void setAllRaces(Collection<RacesBean> allRaces) {
		this.allRaces = allRaces;
	}

	public RacesBean getEditRace() {
		return editRace;
	}

	public void setEditRace(RacesBean editRace) {
		this.editRace = editRace;
	}


	public UsersBean getUser() {
		return user;
	}


	public void setUser(UsersBean user) {
		this.user = user;
	}


	public Boolean getValidateEntireForm() {
		return validateEntireForm;
	}


	public void setValidateEntireForm(Boolean validateEntireForm) {
		this.validateEntireForm = validateEntireForm;
	}

	
	
	
	

}
